package com.mgg.auth.authentication.mobile;


import com.mgg.auth.service.user.UserService;
import com.mgg.common.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class MobileUserDetailService implements UserDetailsService{

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
    private UserService userService;
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.security.core.userdetails.UserDetailsService#
	 * loadUserByUsername(java.lang.String)
	 */
	@Override
	public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
		logger.info("手机号登录:" + phone);
		try {
			UserVO userInfo = userService.getUserByPhone(phone);
			if (userInfo == null) {
				return null;
			}
			String username = userInfo.getUsername();
			String userId = userInfo.getUserId();
			String password = "";
			password = passwordEncoder.encode(password);
			String userStatus = userInfo.getUserStatus();
			Boolean accountNonLocked = true;
			if ("0".equals(userStatus)) {
				accountNonLocked = false;
			}
			return new User(userId, password,true,true,true,accountNonLocked,
					AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER,ROLE_ANONYMOUS"));
		} catch (Exception e) {
			e.printStackTrace();
			throw new UsernameNotFoundException("用户查询失败");
		}
	}
}
